package com.yvtian.admin.controller;

import com.yvtian.admin.pojo.SysUser;
import com.yvtian.admin.service.SysUserService;
import com.yvtian.admin.vo.UserInfoResponse;
import com.yvtian.annotation.Log;
import com.yvtian.constants.TokenConstants;
import com.yvtian.entity.Result;
import com.yvtian.entity.StatusCode;
import com.yvtian.enums.OperatorType;
import com.yvtian.utils.AsyncUtil;
import com.yvtian.utils.StringHelper;
import com.yvtian.utils.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;

@Slf4j
@RequestMapping("file")
@RestController
public class FileController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private AsyncUtil asyncUtil;

    @Log(value = "上传头像", isSave = true, operType = OperatorType.EXPORT)
    @RequestMapping(value = "/upLoad/avatar", method = RequestMethod.POST)
    public Result upLoadUserAvatar(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile.getSize() > 1024 * 1024 * 2) {
            return new Result(false, "上传的最大文件为2M", StatusCode.PARAMS_IN_ERROR);
        }
        String filename = multipartFile.getOriginalFilename();
        if (filename == null) {
            return new Result(false, "文件名为空", StatusCode.PARAMS_IN_ERROR);
        }

        String userId = (String) request.getAttribute(TokenConstants.JWT_USER_ID);
        UserInfoResponse userInfo = userService.findUserById(userId);

        //获取文件后缀名
        String substring = filename.substring(filename.lastIndexOf("."));

        File directory = new File(SystemConstant.USER_AVATAR_PATH);
        boolean mkdirFlag = true;
        if (!directory.exists()) {
            mkdirFlag = directory.mkdirs();
        }

        if (!mkdirFlag) {
            return new Result(false, "服务器异常", StatusCode.ERROR);
        }

        String imgName = UUID.randomUUID() + substring;

        File destFile = new File(directory, imgName);

        try {
            //保存用户头像
            multipartFile.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true, "上传失败", StatusCode.ERROR);
        }

        String oldAvatar = userInfo.getAvatar();
        if (!StringHelper.isEmpty(oldAvatar)) {
            asyncUtil.delAvatarImg(directory + "/" + oldAvatar);
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setAvatar(imgName);
        userService.updateUser(sysUser);
        return new Result(true, "上传成功", StatusCode.OK, imgName);
    }

    @RequestMapping(value = "/avatar/{avatar}", method = RequestMethod.GET)
    public void upLoadUserAvatar(@PathVariable(value = "avatar") String avatar,HttpServletResponse response){
        File userAvatar = new File(SystemConstant.USER_AVATAR_PATH + avatar);
        if (!userAvatar.exists()){
            return;
        }

        try {
            byte[] imageBytes = Files.readAllBytes(userAvatar.toPath());

            response.getOutputStream().write(imageBytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
